import 'package:citiesocial/_include.dart';

///
///图片轮播图组件
///
class BannerImage extends StatefulWidget {
  final List list;
  final OnBannerClick onClick;

  BannerImage(this.list, {this.onClick});

  @override
  State<StatefulWidget> createState() => _BannerIndexState();
}

class _BannerIndexState extends State<BannerImage> {
  final height = 180.0,
      _indicatorSize = 7.5,
      _indicatorBetween = 3.0,
      _indicatorMargin = 15.0;

  PageController _pageController;
  int _position = 0;

  _BannerIndexState() : super() {
    _pageController = PageController();
    _pageController.addListener(() {
      int page = _pageController.page.round();
      if (page != _position) {
        setState(() {
          _position = page;
        });
      }
    });
  }

  void onBannerItemTap(int index) {}

  List<Widget> _getIndicator() {
    if (widget.list == null || widget.list.length == 0) return [];
    List<Widget> result = List();
    for (int index = 0; index < widget.list.length; index++) {
      var circle = Container(
        margin: EdgeInsets.symmetric(horizontal: _indicatorBetween),
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: _position == index ? Colors.white : Colors.grey,
        ),
        width: _indicatorSize,
        height: _indicatorSize,
      );
      result.add(circle);
    }
    return result;
  }

  @override
  Widget build(BuildContext context) => Container(
        child: Stack(
          children: <Widget>[
            PageView.builder(
              itemBuilder: (BuildContext context, int index) {
                return GestureDetector(
                  child: Image(
                    image: CachedNetworkImageProvider(widget.list[index]),
                    fit: BoxFit.cover,
                  ),
                  onTap: widget.onClick == null
                      ? () => onBannerItemTap(index)
                      : widget.onClick,
                );
              },
              itemCount: widget.list == null ? 0 : widget.list.length,
              controller: _pageController,
            ),
            Container(
              alignment: AlignmentDirectional.bottomCenter,
              margin: EdgeInsets.all(_indicatorMargin),
              child: Row(
                children: _getIndicator(),
              ),
            ),
          ],
        ),
        height: height,
      );
}
